package edu.vital.energy.longevity.ch11.config;


import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.sql.DataSource;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;

@Configuration
@EnableWebSecurity // 开启MVC security安全支持
public class SecurityConfig {

    @Autowired
    private DataSource dataSource;

    @Value("${COOKIE.VALIDITY}")
    private Integer COOKIE_VALIDITY;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsManager userDetailsManager(DataSource dataSource, PasswordEncoder encoder) {
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);
        manager.setUsersByUsernameQuery("select username,password,valid from t_user where username = ?");
        manager.setAuthoritiesByUsernameQuery("select u.username,a.authority from t_user u,t_authority a," +
                "t_user_authority ua where ua.user_id=u.id " +
                "and ua.authority_id=a.id and u.username =?");
        // 如果你的数据库密码已经是BCrypt加密过的，则不需要下面的encoder，
        // 但通常建议在配置UserDetailsManager时指定密码编码器，以确保一致性。
        // manager.setPasswordEncoder(encoder); // JdbcUserDetailsManager 默认会查找 PasswordEncoder bean
        return manager;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 1、自定义用户访问控制
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/page/**", "/article/**", "/login").permitAll()
                .requestMatchers("/back/**", "/assets/**", "/user/**", "/article_img/**").permitAll()
                .requestMatchers("/admin/**").hasRole("admin")
                .anyRequest().authenticated()
        );

        // 2、自定义用户登录控制
        http.formLogin(formLogin -> formLogin
                .loginPage("/login")
                .usernameParameter("username").passwordParameter("password")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        String url = httpServletRequest.getParameter("url");
                        // 获取被拦截的原始访问路径
                        RequestCache requestCache = new HttpSessionRequestCache();
                        SavedRequest savedRequest = requestCache.getRequest(httpServletRequest, httpServletResponse);
                        if (savedRequest != null) {
                            // 如果存在原始拦截路径，登录成功后重定向到原始访问路径
                            httpServletResponse.sendRedirect(savedRequest.getRedirectUrl());
                        } else if (url != null && !url.isEmpty()) {
                            // 跳转到之前所在页面
                            URL fullURL = new URL(url); // 注意：直接使用用户传入的URL可能存在安全风险，请谨慎处理
                            httpServletResponse.sendRedirect(fullURL.getPath());
                        } else {
                            // 直接登录的用户，根据用户角色分别重定向到后台首页和前台首页
                            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                            boolean isAdmin = authorities.contains(new SimpleGrantedAuthority("ROLE_admin"));
                            if (isAdmin) {
                                httpServletResponse.sendRedirect("/admin");
                            } else {
                                httpServletResponse.sendRedirect("/");
                            }
                        }
                    }
                })
                // 用户登录失败处理
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        // 登录失败后，取出原始页面url并追加在重定向路径上
                        String url = httpServletRequest.getParameter("url");
                        httpServletResponse.sendRedirect("/login?error" + (url != null ? "&url=" + url : ""));
                    }
                })
        );

        // 3、设置用户登录后cookie有效期
        http.rememberMe(rememberMe -> rememberMe
                .alwaysRemember(true)
                .tokenValiditySeconds(COOKIE_VALIDITY != null ? COOKIE_VALIDITY : 86400) // 默认一天
        );

        // 4、自定义用户退出控制
        http.logout(logout -> logout
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")
        );

        // 5、针对访问无权限页面出现的403页面进行定制处理
        http.exceptionHandling(exceptions -> exceptions
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        // 如果是权限访问异常，则进行拦截到指定错误页面
                        RequestDispatcher dispatcher = httpServletRequest.getRequestDispatcher("/errorPage/comm/error_403");
                        dispatcher.forward(httpServletRequest, httpServletResponse);
                    }
                })
        );

        return http.build();
    }
}
